<template>
  <div class="m-view-applySoleList m-window">
    <div class="m-condition">
      <el-form :model="searchForm" ref="ruleForm">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="工厂代码：" label-width="88px">
              <el-input
                v-model="searchForm.factory"
                placeholder="输入工厂代码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="零件类型：" label-width="88px">
              <el-input
                v-model="searchForm.partType"
                placeholder="输入零件类型"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="物料描述（材质）：" label-width="140px">
              <el-input
                v-model="searchForm.matDescription"
                placeholder="输入物料描述"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="日期：" label-width="55px">
              <el-date-picker
                v-model="searchForm.createDate"
                type="date"
                placeholder="输入日期"
                value-format="yyyy-MM-dd"
                :editable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="审核状态：" label-width="88px">
              <el-select
                placeholder="审核状态"
                v-model="searchForm.state"
                clearable
                @change="changeState"
              >
                <el-option
                  v-for="(item, index) in statusItem"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="申购单号：" label-width="88px">
              <el-input
                v-model="searchForm.purchaseNum"
                placeholder="输入单号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="模具编号：" label-width="88px">
              <el-input
                v-model="searchForm.mouldNum"
                placeholder="请输入模具编号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item
              label="审核人："
              label-width="88px"
              prop="personSelect"
            >
              <el-select
                placeholder="审核人"
                v-model="searchForm.auditor"
                clearable
                @change="changeAuditor"
              >
                <el-option
                  v-for="(item, index) in personItem"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="verify()">提交审核</el-button>
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="handleExport">导出文件</el-button>
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="openImportDialog"
              >导入文件</el-button
            >
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="getPurchaseRequest"
              >查询</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="m-agTable m-bottom m-applySoleListTable">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham m-agCenter"
        ref="applySoleRef"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="rowData"
        v-loading="loading"
      ></ag-grid-vue>
    </div>
    <div class="m-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page="searchForm.current"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="searchForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchForm.total"
      ></el-pagination>
    </div>

    <!-- 导入文件 -->
    <el-dialog
      title="导入物料模板"
      v-if="importDialogVisible"
      :visible.sync="importDialogVisible"
      width="50%"
      :before-close="importHandleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <importFile
        :moduleName="moduleName"
        @setImportData="getImportData"
        :closeImportDialog="importDialogVisible"
        :colorStyle="colorStyle"
        :tempUrl="tempUrl"
      ></importFile>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importHandleClose">取消</el-button>
        <el-button type="primary" @click="saveImportData">导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import gridOptions from "lesso-common/public/gridOptions";
import _Api from "@/api";
import importFile from "@/components/importFile.js";
import constant from "@/public/constant";

export default {
  data() {
    return {
      colorStyle: "#f56c6c",
      searchForm: {
        factory: "", //工厂代码
        partType: "", //零件类型
        matDescription: "", //材质
        createDate: "", //日期
        purchaseNum: "", //单号
        mouldNum: "", //模具编号
        state: null, //审核状态
        auditor: null, //审核人 id
        size: 30,
        current: 1,
        total: 0,
      },
      statusValue: "", //状态中文值

      statusItem: [
        { code: 0, name: "待提交" },
        { code: 1, name: "待审" },
        { code: 2, name: "通过" },
        { code: 3, name: "退回" },
      ], //状态列表

      personItem: [], //审核人列表

      //ag-grid 配置项
      gridOptions: null,
      columnDefs: null,

      rowData: [], //  表格数据
      loading: false, //加载条
      importDialogVisible: false,
      moduleName: "applySoleList",
      tempUrl: "", //物料模板线下下载地址
      selectAuditor: {}, //选中审核人
    };
  },
  props: {
    addTab: {
      type: Function,
    },
  },
  components: {
    importFile,
  },
  mounted() {
    this.getApplySoleTemp();

    this.getReviewerList();
    this.searchForm.createDate = this.$utils.dateFormat(
      "yyyy-MM-dd",
      new Date()
    ); //设置默认日期今日

    this.getPurchaseRequest();
  },
  created() {
    this.gridOptions = gridOptions();
    this.columnDefs = [
      {
        headerName: "申购单号",
        field: "purchaseNum",
        checkboxSelection: true,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
        width: 160,
      },
      { headerName: "序号", field: "sequence", width: 70 },
      { headerName: "模具编号", field: "mouldNum", width: 90 },
      {
        headerName: "SAP名称",
        field: "sapName",
        width: 90,
      },
      { headerName: "零件类型", field: "partType", width: 90 },
      { headerName: "零件名称", field: "partName", width: 90 },
      { headerName: "材质", field: "matDescription", width: 90 },
      { headerName: "物料编码", field: "matNum", width: 100 },
      // { headerName: "热处理状态/硬度", field: "hardness", width: 130 },
      // { headerName: "是否倒角", field: "chamfer", width: 90 },
      { headerName: "长", field: "length", width: 52 },
      {
        headerName: "长度公差",
        field: "lengthTolerance",
        width: 90,
        cellRenderer: (params) => {
          if (params.value.indexOf("，") != -1) {
            let numArr = params.value.split("，");
            return (
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[0] +
              "</div>" +
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[1] +
              "</div>"
            );
          } else if (params.value.indexOf(",") != -1) {
            let numArr = params.value.split(",");
            return (
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[0] +
              "</div>" +
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[1] +
              "</div>"
            );
          }
        },
      },
      { headerName: "宽", field: "width", width: 52 },
      {
        headerName: "宽度公差",
        field: "widthTolerance",
        width: 90,
        cellRenderer: (params) => {
          if (params.value.indexOf("，") != -1) {
            let numArr = params.value.split("，");
            return (
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[0] +
              "</div>" +
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[1] +
              "</div>"
            );
          } else if (params.value.indexOf(",") != -1) {
            let numArr = params.value.split(",");
            return (
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[0] +
              "</div>" +
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[1] +
              "</div>"
            );
          }
        },
      },
      { headerName: "高", field: "heigth", width: 52 },
      {
        headerName: "高度公差",
        field: "heigthTolerance",
        width: 90,
        cellRenderer: (params) => {
          if (params.value.indexOf("，") != -1) {
            let numArr = params.value.split("，");
            return (
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[0] +
              "</div>" +
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[1] +
              "</div>"
            );
          } else if (params.value.indexOf(",") != -1) {
            let numArr = params.value.split(",");
            return (
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[0] +
              "</div>" +
              "<div style='word-wrap:break-word;word-break: break-all !important;'>" +
              numArr[1] +
              "</div>"
            );
          }
        },
      },
      { headerName: "数量", field: "amount", width: 68 },
      { headerName: "硬度", field: "hardness", width: 68 },
      { headerName: "是否倒角", field: "chamfer", width: 90 },
      { headerName: "单重", field: "pieceWeight", width: 68 },
      { headerName: "总重", field: "grossWeight", width: 68 },
      { headerName: "设计", field: "designer", width: 68 },
      { headerName: "工厂代码", field: "factory", width: 90 },
      {
        headerName: "审核状态",
        field: "state",
        width: 90,
        valueFormatter: (params) => {
          for (let i = 0; i < this.statusItem.length; i++) {
            const status = this.statusItem[i];
            if (status.code === params.value) {
              return status.name;
            }
          }
          return params.value;
        },
      },
      { headerName: "创建日期", field: "createDate", width: 90 },
    ];
    this.gridOptions.defaultColDef.autoHeight = true;
    this.gridOptions.defaultColDef.cellClass = "cell-wrap-text";
  },
  beforeMount() {},
  methods: {
    // 查询列表
    getPurchaseRequest() {
   
      this.loading = true;
      let params = {
        size: this.searchForm.size,
        current: this.searchForm.current,
        leParams: {
          state: 3,
        },
        geParams: {
          state: 0,
        },
        eqParams: {
          state: this.searchForm.state,
        }, //精确查询
        likeParams: {
          createDate: this.searchForm.createDate,
          factory: this.searchForm.factory,
          matDescription: this.searchForm.matDescription,
          mouldNum: this.searchForm.mouldNum,
          partType: this.searchForm.partType,
          purchaseNum: this.searchForm.purchaseNum,
        }, //模糊查询
        orderBy: "createDate",
        isAsc: "false",
      };
      console.log(params, "params");
      _Api
        .getPurchaseRequestList(params)
        .then((response) => {
          let data = response.data;
          this.searchForm.total = data.total;
          if (data.code == 1 && data.total != 0) {
            this.rowData = data.rows;
            this.loading = false;
          } else {
            this.loading = false;
            this.rowData = [];
          }
        })
        .catch((err) => {
          this.rowData = [];
          this.loading = false;
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    //   审核
    verify() {
      let rows = this.gridOptions.api.getSelectedRows();

      if (rows.length <= 0) {
        this.$alert("提示：请选择需要审核的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }

      if (!this.searchForm.auditor) {
        this.$alert("提示：请选择需要审核人", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
        let updateRows = [];
        rows.forEach((item) => {
          let obj = {};
          obj = item;
          obj.auditorMsgId = this.searchForm.auditor; //审核人id
          // auditor
          obj.state = 1;
          obj.modifyer = constant.user.loginName; //登录人名称
          obj.modifyerId = constant.user.id; //登录人Id
          obj.modifyDate = this.curentTime(); //获取当前时间
          obj.auditor = this.selectAuditor.name; //获取选中审核人名称

          updateRows.push(obj);
        });

        _Api
          .submiteviewer(updateRows)
          .then((response) => {
            let data = response.data;
            if (data.code == 1) {
              this.$message({
                message: data.msg,
                type: "success",
              });

              this.getPurchaseRequest();
              //  this.addTab({
              //     cName: "待审核列表",
              //     name: "awaitVerifyList",
              //     completed: false,
              //   });
            } else {
              this.$message({
                message: data.msg,
                type: "warning",
              });
            }
          })
          .catch((err) => {
            this.$alert(err.data.message, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          });
      }
    },
    // 打开导入模板弹窗
    openImportDialog() {
      this.importDialogVisible = true;
    },
    // 保存导入
    saveImportData() {
      let params = {
        requestList: this.importData,
        creatorId: constant.user.id,
        creator: constant.user.employeeName,
        createDate: this.curentTime(),
      };
      _Api
        .importRequest(params)
        .then((response) => {
          let data = response.data;
          if (data.code == 1) {
            this.$message({
              message: data.msg,
              type: "success",
            });
            this.importDialogVisible = false;
            this.getPurchaseRequest();
          } else {
            this.$message({
              message: data.msg,
              type: "warning",
            });
          }
        })
        .catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    // 获取当前日期时间
    curentTime() {
      var now = new Date();

      var year = now.getFullYear(); //年
      var month = now.getMonth() + 1; //月
      var day = now.getDate(); //日

      var hh = now.getHours(); //时
      var mm = now.getMinutes(); //分
      var ss = now.getSeconds(); //分

      var clock = year + "-";

      if (month < 10) clock += "0";

      clock += month + "-";

      if (day < 10) clock += "0";

      clock += day + " ";

      if (hh < 10) clock += "0";

      clock += hh + ":";
      if (mm < 10) clock += "0";
      clock += mm + ":";

      if (ss < 10) clock += "0";
      clock += ss;
      return clock;
    },

    // 关闭导入模板弹窗
    importHandleClose(done) {
      //   done();
      this.importDialogVisible = false;
    },

    // 获取导入数据
    getImportData(val) {
      this.importData = val;
      console.log(this.importData, "获取导入数据");
    },
    // 获取物料申购导入模板
    getApplySoleTemp() {
      this.tempUrl = `${window.location.origin}/static/file/武汉联塑精密模具采购流程表格模板.xlsx`;
    },
    // 导出文件
    handleExport() {
      let rows = this.gridOptions.api.getSelectedRows();
      console.log(rows, "导出");

      if (rows.length <= 0) {
        this.$alert("提示：请选择需要导出的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }

      let purNumArr = [];
      rows.forEach((item) => {
        purNumArr.push(item.purchaseNum);
      });

      _Api
        .exportedRequest([...new Set(purNumArr)])
        .then((response) => {
          let data = response.data;

          if (data.code == 1 && data.total != 0) {
            let originRows = data.rows;
            console.log(originRows, "originRows");
            let sheetHeaderCN = [];
            let sheetHeaderEN = [];
            let columnDefsHead = this.$refs.applySoleRef.columnDefs;
            columnDefsHead.forEach((item) => {
              sheetHeaderCN.push(item.headerName);
              sheetHeaderEN.push(item.field);
            });
            let dataSource = [];

            originRows.forEach((item) => {
              for (let i = 0; i < this.statusItem.length; i++) {
                const status = this.statusItem[i];

                if (status.code == item.state) {
                  this.statusValue = status.name;
                }
              }

              dataSource.push({
                申购单号: item.purchaseNum,
                序号: item.sequence,
                模具编号: item.mouldNum,
                SAP名称: item.sapName,
                零件类型: item.partType,
                零件名称: item.partName,
                材质: item.matDescription,
                物料编码: item.matNum,
                长: item.length,
                长度公差: item.lengthTolerance,
                宽: item.width,
                宽度公差: item.widthTolerance,
                高: item.heigth,
                高度公差: item.heigthTolerance,
                数量: this.amount,
                硬度: item.hardness,
                是否倒角: item.chamfer,
                单重: item.pieceWeight,
                总重: item.grossWeight,
                设计: item.designer,
                工厂代码: item.factory,
                审核状态: this.statusValue,
                创建日期: item.createDate,
              });
            });
            console.log(dataSource, "dataSource");
            let fileName = "物料单申请.xlsx";
            this.$utils.exportExcel({
              data: dataSource,
              sheetHeader: sheetHeaderCN,
              fileName: fileName,
            });
          } else {
            originRows = [];
          }
        })
        .catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    // 获取审核人
    getReviewerList() {
      let params = {
        type: 1,
      };
      _Api
        .getReviewer(params)
        .then((response) => {
          console.log(response, "获取审核人");
          let data = response.data;
          if (data.code == 1) {
            let arrList = data.rows;
            arrList.forEach((item) => {
              let obj = {};
              obj.code = item.id;
              obj.name = item.name;
              obj.sapgh = item.sapgh;
              this.personItem.push(obj);
            });
          } else {
            this.personItem = [];
          }
        })
        .catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    //  选中审核人名字
    changeAuditor(vId) {
      this.selectAuditor = this.personItem.find((item) => {
        return item.code === vId;
      });
    },
    // 改变审核状态
    changeState(data) {
      this.searchForm.state = data;
      this.getPurchaseRequest();
    },
    // 每页显示条数改变回调
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.getPurchaseRequest();
    },
    // 页码改变回调
    handleCurrentChange(val) {
      this.searchForm.current = val;
      this.getPurchaseRequest();
    },
    // 点击上一页回调
    handlePrevClick(val) {
      this.searchForm.current = val;
    },
    // 点击下一页回调
    handleNextClick(val) {
      this.searchForm.current = val;
    },
  },
};
</script>

<style lang="less">
.cell-wrap-text {
  white-space: normal !important;
}
</style>